import React, { useState } from 'react';
import { Modal } from 'antd';
// The default `position: "absolute"` does not work well with React 16+, so draggabilly must be used.
import Draggable from 'react-draggable';
import { CloseOutlined } from '@ant-design/icons';

// styles
import styles from './index.less';

export default ({ title, children, dragModalClassName, style, ...rest }) => {
  const draggleRef = React.createRef();
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const onStartHandle = (event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) return;
    if (targetRect) {
      setBounds({
        left: -targetRect.left + uiData.x,
        right: clientWidth - (targetRect.right - uiData.x),
        top: -targetRect.top + uiData.y,
        bottom: clientHeight - (targetRect.bottom - uiData.y),
      });
    }
  };
  return (
    <Modal
      style={
        style ? style : { top: 20, left: '50%', transform: 'translate(-50%)' }
      }
      wrapClassName={styles.modalWrap}
      title={
        <div
          style={{
            width: 'calc(100% - 20px)',
            cursor: 'move',
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
          }}
          title={title}
          onMouseOver={() => {
            if (disabled) {
              setDisabled(false);
            }
          }}
          onMouseOut={() => {
            setDisabled(true);
          }}
          onFocus={() => {}}
          onBlur={() => {}}
        >
          {title}
        </div>
      }
      modalRender={(modal) => (
        <Draggable
          disabled={disabled}
          bounds={bounds}
          onStart={(event, uiData) => onStartHandle(event, uiData)}
        >
          <div
            ref={draggleRef}
            className={`${dragModalClassName || ''} ${styles.dialogContainer}`}
          >
            {modal}
          </div>
        </Draggable>
      )}
      {...rest}
    >
      {children}
    </Modal>
  );
};
